from django.conf import settings
from django_redis import get_redis_connection
from rest_framework import serializers

from users.models import Address

import re

from rest_framework_jwt.settings import api_settings

from celery_tasks.email.tasks import send_verify_email

from django.core.mail import send_mail

from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from areas.models import Area

class AreasSerializer(serializers.ModelSerializer):

    class Meta:
        model = Area
        fields = ('id', 'name')


class AddressSerializer(serializers.ModelSerializer):
    '''保存用户地址序列化器'''
    # 显示指明
    city= serializers.StringRelatedField(read_only=True)
    district= serializers.StringRelatedField(read_only=True)
    province= serializers.StringRelatedField(read_only=True)

    city_id= serializers.IntegerField(write_only=True)
    district_id=serializers.IntegerField(write_only=True)
    province_id=serializers.IntegerField(write_only=True)
    class Meta:
        model = Address
        fields = ('city_id', 'district_id', 'province_id', 'email', 'mobile', 'place', 'receiver', 'tel',
                  'title','city','district','province','id')

    # 验证手机号格式
    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式错误')
        return value

    def create(self, validated_data):

        # 获取用户对象
        user = self.context['request'].user
        # 将用户对象添加到验证后的数据中
        validated_data['user'] = user
        # 保存操作
        address = Address.objects.create(**validated_data)

        # 返回地址对象
        return address